"use strict";
$(document).ready(function() {

  var refreshImages = function(productId, currentName, imageDiv, listDiv) {
    if($.trim(productId) == '') {
      $(listDiv).html('');
      $(imageDiv).html('');
      return;
    }
    var name = currentName;    
    $.ajax({
      url : 'product/' + productId + '/images.json',
      method : 'GET',
      success : function(ret) {
        var html = '';
        for (var i = 0; i < ret.length; i++) {
          var file = ret[i];
          if (!name) {
            name = file.name;
          }
          if (i > 0) {
            html += '&nbsp;';
          }
          html += '<a href="javascript:void(0);"';
          if (name == file.name) {
            html += ' class="selected"';
          }
          html += '>' + file.name + '</a>';
        }
        $(listDiv).html(html);
        if (name && name.length > 0) {
          $(imageDiv).html('<img src="product/' + productId + '/' + name + '" />');
        } else {
          $(imageDiv).html('');
        }
      }
    });
  };
  
  /**
   * 更新货架视图
   * @param id 货架id
   * @param layers 货架层数
   * @param cols 货架列数
   * @param 生成了视图html后执行的回调
   */
  var refreshRackView = function(id, layers, cols, cb) {
    var loadIndex = layer.load();
    $.ajax({
      url : 'stock/list/' + id,
      method : 'GET',
      data : {
        _method : 'GET'
      }
    }).done(function( data, textStatus, jqXHR ) {
      var infos = {};
      for(var i = 0; i < data.length; i++) {
        var info = data[i];
        infos[info.layer + '_' + info.col] = info;
      }
      var html = '<h2>';
      html += id;
      html += '号货架</h2>';
      html += '<table class="table table-bordered table-condensed table-hover">';
      for(var i = 1; i <= layers; i++) {
        html += '<tr>';
        for(var j = 1; j <= cols; j++) {         
          var info = infos[i + '_' + j];
          html += '<td class="text-center"><div id="r_' + i + '_' + j + '"';
          if(info) {
            html += ' title="' + info.productName + '"';
            html += ' style="background-color: ' + info.productColor + '"';
            html += '><a href="javascript:void(0);" data-id="' + info.id + '">';
          } else {
            html += '>';
          }
          html += '<span>';
          html += i + '层' + j + '号';
          html += '</span>';
          if(info) {
            html += '</a>';
          }
          html += '</div></td>';
        }
        html += '</tr>';
      }
      html += '</table>';
      cb.call(this, html);
    }).always(function(){
      layer.close(loadIndex);      
    });
  };
  
  var rackDlg;
  var rackLayers;
  var rackCols;
  $('.rack a').click(function(){
    var $this = $(this);
    var id = $this.data('id');
    rackLayers = $this.data('layers');
    rackCols = $this.data('cols');
    refreshRackView(id, rackLayers, rackCols, function(html){
      $('#rackdiv').html(html);
      rackDlg = layer.open({
        type : 1,
        title : false,
        area : '800px',
        closeBtn : true,
        shadeClose : false,
        content : $('#rackdiv')      
      });
    });
  });

  var uploader;
  var viewDlg;
  var viewStock;
  $('#rackdiv').on('click', 'td a', function() {
    var id = $(this).data('id');
    var loadIndex = layer.load();
    $.ajax({
      url : 'stock/' + id,
      method : 'GET',
      data : {
        _method : 'GET'
      },
      success : function(ret) {
        layer.close(loadIndex);
        viewDlg = layer.open({
          type : 1,
          title : false,
          area : '800px',
          closeBtn : true,
          shadeClose : false,
          content : $('#viewdiv')
        });
        viewStock = ret;
        $('#view_id').text(viewStock.id);
        if(admin) {
          if(!uploader) {
            //容器div不可见时初始化出的按钮无法点击
            uploader = WebUploader.create({
              // 选完文件后，是否自动上传。
              auto : true,
              // swf文件路径
              swf : 'vendors/webuploader/Uploader.swf',
              // 文件接收服务端。
              server : 'product/uploadImage',
              // 选择文件的按钮。可选。
              // 内部根据当前运行是创建，可能是input元素，也可能是flash.
              pick : '#filePicker',

              // 只允许选择图片文件。
              accept : {
                title : 'Images',
                extensions : 'gif,jpg,jpeg,bmp,png',
                mimeTypes : 'image/*'
              }
            });
            uploader.on('uploadBeforeSend', function(object, data, headers) {
              data.id = viewStock.productId;
            });
            uploader.on('uploadSuccess', function(file, resp) {
              // alert(resp.id + ' - ' + resp.name);
              refreshImages(viewStock.productId, resp.name, $('#viewdiv .images'), $('#view_images'));
            });
          }
          $('#viewdiv form').get(0).reset();
          $('#view_productid').val(viewStock.productId).data('oval', viewStock.productId);
          $('#view_productname').val(viewStock.productName);
          $('#view_vendor').val(viewStock.vendor);
          $('#view_rackid').val(viewStock.rackId).data('oval', viewStock.rackId);
          $('#view_layer').val(viewStock.layer);
          $('#view_col').val(viewStock.col);
          //$('#view_rackaddress').text(viewStock.rackAddress);
          $('#view_quantity').val(viewStock.quantity);           
          $('#viewdiv form').validate().resetForm();
        } else {
          $('#view_productid').text(viewStock.productId);
          $('#view_productname').text(viewStock.productName);
          $('#view_vendor').text(viewStock.vendor);
          $('#view_rackid').text(viewStock.rackId);
          $('#view_layer').text(viewStock.layer);
          $('#view_col').text(viewStock.col);
          //$('#view_rackaddress').text(viewStock.rackAddress);
          $('#view_quantity').text(viewStock.quantity);          
        }
        refreshImages(viewStock.productId, null, $('#viewdiv .images'), $('#view_images'));
      }
    });
  });  

  $('#btndel').on('click', function(){
    //删除图片
    var name = $('#view_images a.selected').text();
    if(!name || name == '') {
      return;
    }
    $.ajax({
      url : 'product/' + viewStock.productId + '/' + name + '.json',
      method : 'POST',
      data: {
        '_method' : 'DELETE'
      }
    }).done(function( data, textStatus, jqXHR ){
      if(!data) {
        return;
      }
      refreshImages(viewStock.productId, null, $('#viewdiv .images'), $('#view_images'));
    });
  });
  $('#view_images').on('click', 'a', function() {
    var $this = $(this);
    var productId = viewStock.productId;
    $('#view_images a').removeClass('selected');
    $this.addClass('selected');
    $('#viewdiv .images').html('<img src="product/' + productId + '/' + $this.text() + '" />');
  });  
  if(!admin) {
    $('#viewdiv .userdlg-bbar .btn-primary').click(function() {
      layer.close(viewDlg);
    });    
  } else {
    // 编辑处理
    $('#viewdiv form').validate({
      rules : {
        productid : {
          required : true
        },
        productname : {
          required : true
        },
        vendor : {
          required : true
        },
        rackid : {
          required : true
        },
        layer: {
          required : true,
          digits: true,
          min: 1
        },
        col: {
          required : true,
          digits: true,
          min: 1
        },
        quantity: {
          required : true,
          digits: true,
          min: 1
        }
      },
      messages : {
        productid : {
          required : '产品编号不能为空'
        },
        productname : {
          required : '产品名称不能为空'
        },
        vendor : {
          required : '生产厂家不能为空'
        },
        rackid : {
          required : '货架编号不能为空'
        },
        layer: {
          required : '所在层必须填写',
          digits: '所在层必须是整数',
          min: '所在层必须大于0'
        },
        col: {
          required : '所在号必须填写',
          digits: '所在号必须是整数',
          min: '所在号必须大于0'
        },
        quantity: {
          required : '产品数量必须填写',
          digits: '产品数量必须是整数',
          min: '产品数量必须大于0'
        }
      },
      errorClass : 'has-error',
      validClass : 'has-success',
      highlight : function(element, errorClass, validClass) {
        var $c = $(element).closest('div.form-group');
        $c.addClass(errorClass).removeClass(validClass);
      },
      unhighlight : function(element, errorClass, validClass) {
        var $c = $(element).closest('div.form-group');
        $c.removeClass(errorClass).addClass(validClass);
      }
    });
    $('#viewdiv .userdlg-bbar .btn-default').click(function() {
      layer.close(viewDlg);
    });
    $('#view_productid').blur(function(){
      var $this = $(this);
      var productId = $this.val();
      var oldValue = $this.data('oval');
      if(productId == oldValue) {
        return;
      }
      if(productId == '') {
        $('#view_productname').val('');
        $('#view_vendor').val('');
        return;
      }
      $.ajax({
        url : 'product/' + productId,
        method : 'GET',
        data : {
          _method : 'GET'
        }
      }).done(function(data, textStatus, jqXHR){
        if(!data) {
          alert('产品编号不存在！');
          $this.focus();
        } else {
          $this.data('oval', productId);
          $('#view_productname').val(data.name);
          $('#view_vendor').val(data.vendor);       
          refreshImages(productId, null, $('#viewdiv .images'), $('#view_images'));   
        }
      });
    });
    $('#view_rackid').blur(function(){
      var $this = $(this);
      var rackId = $this.val();
      var oldValue = $this.data('oval');
      if(rackId == oldValue) {
        return;
      }
      $.ajax({
        url : 'rack/' + rackId,
        method : 'GET',
        data : {
          _method : 'GET'
        }
      }).done(function(data, textStatus, jqXHR){
        if(!data) {
          alert('货架编号不存在！');
          $this.focus();
        } else {
          $this.data('oval', rackId);
        }
      });
    });

    $('#viewdiv .userdlg-bbar .btn-primary').click(function() {
      if (!$('#viewdiv form').valid()) {
        layer.alert('请修正输入错误！');
      } else {
        var stock = $.extend({}, viewStock);
        stock.productId = $('#view_productid').val();
        stock.productName = $('#view_productname').val();
        stock.vendor = $('#view_vendor').val();
        stock.rackId = $('#view_rackid').val();
        stock.layer = $('#view_layer').val();
        stock.col = $('#view_col').val();
        stock.quantity = $('#view_quantity').val();        
        stock['_method'] =  'PUT';
        $.ajax({
          url : 'stock/' + viewStock.id,
          method : 'POST',
          data : stock,
          success : function(ret) {
            layer.close(viewDlg);
            refreshRackView(viewStock.rackId, rackLayers, rackCols, function(html){
              $('#rackdiv').html(html);
            });
          }
        });
      }
    });
  }
});